package dj.dwr;

import java.util.Collection;

import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;

import dj.Constant;

public class UpdatePageInfo {

	/**
	 * 给所有用户发送消息
	 * 
	 * @param msg
	 */
	public void sendMsg(String msg) {
		callScript("index.jsp", "show", msg);
	}

	/**
	 * 更新在线用户数量
	 */
	public void getUsersInfo() {
		callScript("index.jsp", "reloadOnlineUser", Constant.onlineUser.size());
	}

	@SuppressWarnings("deprecation")
	public static void callScript(String page, String method, Object... params) {

		// 得到上下文
		WebContext contex = WebContextFactory.get();

		// 得到要推送到 的页面
		Collection<ScriptSession> sessions = contex.getScriptSessionsByPage(contex.getContextPath() + "/" + page);
		
		if(sessions.size() < 1) {
			sessions = contex.getScriptSessionsByPage(contex.getContextPath() + "/");
		}

		Util util = new Util(sessions);
		
		ScriptBuffer sb = new ScriptBuffer();
		sb.appendCall(method, params);
		
		util.addScript(sb);
	}
}
